﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Management;
using System.Collections;

namespace NetWorkCardConnect
{
    public partial class Form1 : Form
    {
        private int _state = 0;
        private int time = 0;
        public Form1()
        {
            InitializeComponent();
            NetWorkList();
            timer1.Interval = 1000;//int.Parse(textBox1.Text.Trim()) *
           
            //if(NetWorkState(cmbNetWork.Text.Trim()))
        }

        /// <summary>
        /// 网卡列表
        /// </summary>
        public void NetWorkList()
        {
            string manage = "SELECT * From Win32_NetworkAdapter";
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(manage);
            ManagementObjectCollection collection = searcher.Get();
            List<string> netWorkList = new List<string>();

            foreach (ManagementObject obj in collection)
            {
                netWorkList.Add(obj["Name"].ToString());

            }
            this.cmbNetWork.DataSource = netWorkList;

        }

        /// <summary>
        /// 禁用网卡
        /// </summary>5
        /// <param name="netWorkName">网卡名</param>
        /// <returns></returns>
        public bool DisableNetWork(ManagementObject network)
        {
            try
            {
                network.InvokeMethod("Disable", null);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 启用网卡
        /// </summary>
        /// <param name="netWorkName">网卡名</param>
        /// <returns></returns>
        public bool EnableNetWork(ManagementObject network)
        {
            try
            {
                network.InvokeMethod("Enable", null);
                return true;
            }
            catch
            {
                return false;
            }

        }

        /// <summary>
        /// 网卡状态
        /// </summary>
        /// <param name="netWorkName">网卡名</param>
        /// <returns></returns>
        public bool NetWorkState(string netWorkName)
        {
            string netState = "SELECT * From Win32_NetworkAdapter";
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(netState);
            ManagementObjectCollection collection = searcher.Get();
            foreach (ManagementObject manage in collection)
            {
                if (manage["Name"].ToString() == netWorkName)
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 得到指定网卡
        /// </summary>
        /// <param name="networkname">网卡名字</param>
        /// <returns></returns>
        public ManagementObject NetWork(string networkname)
        {
            string netState = "SELECT * From Win32_NetworkAdapter";

            ManagementObjectSearcher searcher = new ManagementObjectSearcher(netState);
            ManagementObjectCollection collection = searcher.Get();

            foreach (ManagementObject manage in collection)
            {
                if (manage["Name"].ToString() == networkname)
                {
                    return manage;
                }
            }

            return null;
        }

        /// <summary>
        /// 开启网卡
        /// </summary>
        public bool startNetWork()
        {
            if (NetWorkState(this.cmbNetWork.SelectedValue.ToString()))
            {
                if (!EnableNetWork(NetWork(this.cmbNetWork.SelectedValue.ToString())))
                {
                    this.InsertLog("开启网卡失败!");
                    return false;
                }
                else
                {
                    this.InsertLog("开启网卡成功!");
                    return true;
                }
            }
            else
            {
                this.InsertLog("网卡己开启!");
                return false;
            }

            //NetWorkList();
        }

        /// <summary>
        /// 关闭网卡
        /// </summary>
        public bool StopNewWork()
        {
            if (NetWorkState(this.cmbNetWork.SelectedValue.ToString()))
            {
                if (!DisableNetWork(NetWork(this.cmbNetWork.SelectedValue.ToString())))
                {
                    this.InsertLog("禁用网卡失败!");
                    return false;
                }
                else
                {
                    this.InsertLog("禁用网卡成功!");
                    return true;
                }
            }
            else
            {
                this.InsertLog("网卡己禁用!");
                return false;
            }

            //NetWorkList();
        }

        /// <summary>
        /// 日志记录
        /// </summary>
        /// <param name="msg"></param>
        public void InsertLog(string msg)
        {
            if (this.richTextBox1.Lines.Count() > 100)
            {
                richTextBox1.Clear();
            }
            string str = String.Format("[{0}]--[{1}]-->{2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), this.cmbNetWork.Text.Trim(), msg) + Environment.NewLine;
            richTextBox1.Text = richTextBox1.Text.Insert(0, str);
        }

        private int startTime = 0;

        /// <summary>
        /// 定时开启或者关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (startTime != time)
            {
                InsertLog((time-startTime - 1) +"秒后执行");
                startTime++;
                return;
            }

            startTime = 0;
            if (_state == 0)  //0表示开启状态，1表示关闭状态
            {
                if (this.StopNewWork())
                {
                    _state = 1;
                }
            }
            else
            {
                if (this.startNetWork())
                {
                    _state = 0;
                }
            }
        }


        private void btnStart_Click(object sender, EventArgs e)
        {
            this.InsertLog("网卡开启中……");
            this.startNetWork();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            this.InsertLog("网卡禁用中……");
            this.StopNewWork();
        }
       
        private void button1_Click(object sender, EventArgs e)
        {
            time = int.Parse(textBox1.Text.Trim());
            startTime = 0;
            if (this.btnTimer.Text.Equals("开启定时"))
            {
                timer1.Enabled = true;
                this.InsertLog("启用定时开启或禁用网卡！");
                this.btnTimer.Text = "关闭定时";
            }
            else
            {
                timer1.Enabled = false;
                this.InsertLog("关闭定时开启或禁用网卡！");
                this.btnTimer.Text = "开启定时";
            }
        }
    }
}
